/**
 * Created by Myron on 2015/8/21.
 */
//AngularJS 控制器
grApp.controller('CartAngularCtrl', ['$scope',
    '$http',
    'ActivityRuleMJFactory',
    'ActivityRuleMSFactory',
    'CartProductFactory',
    function ($scope, $http, activityRuleMJFactory, activityRuleMSFactory, cartProductFactory) {

        $scope.showRemindDiv = false; //显示购物车为空提醒
        $scope.showCartDiv = true; //显示购物车内容
        $scope.showActivityDiv = true; //显示购物车内容
        $scope.showMSotherActivityDiv = false; //显示满送活动额外提醒
        $scope.checkAllStatus = false; //全选按钮状态
        //数据变量
        $scope.GoodsPrice = 0.0;//货物总价 180
        $scope.DiscountPrice = 0.0; //优惠金额 30
        $scope.TotalPrice = 0.0; //购物车总价 150
        $scope.ActivityRuleMJArray = {};//满减活动规则列
        $scope.ActivityRuleMSArray = {};//满送活动规则列
        $scope.CartProductCount = 0;//购物车商品行数量
        $scope.CartProductArray = {};//购物车商品列表
        $scope.WaiMaiPrice=0;
        $scope.temp;
        //页面初始化载入顺序事件
        $scope.RunData = function () {
            var progress = $.AMUI.progress;
            var $modal = angular.element("#my-modal-loading");
            progress.start();
            $modal.modal();
            //页面初始化载入顺序事件
            //1清理购物车无效数据
            cartProductFactory.setProductCheck().then(function (data) {
                //2获取显示购物车被选中商品货物总价格
                cartProductFactory.getGoodsPrice().then(function (data) {
                    $scope.GoodsPrice = data.GoodsPrice;
                    $scope.WaiMaiPrice =data.WaiMaiPrice;
                    console.log(2);
                }).then(function () {
                    //3.显示满减规则列表，并获取优惠金额，计算购物车总价 =GoodsPrice-优惠金额
                    activityRuleMJFactory.getActivityRuleMJ($scope.GoodsPrice-$scope.WaiMaiPrice).then(function (data) {  // 调用承诺API获取数据 .resolve
                        $scope.DiscountPrice = activityRuleMJFactory.getDiscountPrice();
                        $scope.ActivityRuleMJArray = activityRuleMJFactory.getRuleArray();
                        $scope.TotalPrice = $scope.GoodsPrice - $scope.DiscountPrice;
                        if(isNaN($scope.TotalPrice)){
                            $scope.TotalPrice =-0.01;
                        }
                        console.log(3);
                    }).then(function () {
                        //4显示满送规则列表，并对购物车进行数据更新（加入购商品）
                        activityRuleMSFactory.getActivityRuleMS($scope.GoodsPrice-$scope.WaiMaiPrice).then(function (data) {
                            $scope.ActivityRuleMSArray = activityRuleMSFactory.getRuleArray();

                            if(typeof($scope.ActivityRuleMJArray)==='undefined'){
                                $scope.ActivityRuleMJArray = [];
                            }
                            if( $scope.ActivityRuleMSArray!=undefined){
                                $scope.showMSotherActivityDiv=true;
                            }


                            if($scope.ActivityRuleMJArray.length==0 && $scope.ActivityRuleMSArray==undefined){
                                //隐藏活动提示层
                                $scope.showActivityDiv=false;
                            };
                            console.log(4);
                        }).then(function () {
                            //5显示购物车商品
                            cartProductFactory.getProductList().then(function (rows) {
                                $scope.CartProductCount = cartProductFactory.getRows();
                                $scope.CartProductArray = cartProductFactory.getProductArray();
                                if ($scope.CartProductCount == 0) {
                                    $scope.showRemindDiv = true;
                                    $scope.showCartDiv = false;
                                }
                                progress.done();
                                $modal.modal('close');
                                console.log(5);
                            })//5结束
                        });//4结束
                    });//3结束
                });//2结束
                console.log(1);
            });//1结束
        }
        //页面初始化

        $scope.RunData();



        //各种点击事件
        //购物车结算按钮点击事件
        $scope.SubmitBtn = function () {
            if($scope.filter()){
                window.location.href="order/confirmOrder/0";
            }
        }
        //购物车商品删除按钮事件
        $scope.TrashBtn = function (index, product) {
            //$scope.CartProductArray.splice(index, 1);
            $scope.confirmname = product.name;
            $scope.temp=product;

            var $modal = angular.element("#my-confirm");
            $modal.modal({
                relatedTarget: this,
                onConfirm: function (options) {
                    //确定删除执行
                    cartProductFactory.trashProduct($scope.temp).then(function (data) {
                        if (data.code == 0) {
                            //成功
                            $scope.RunData();//重新加载购物车数据
                        } else {
                            alert('删除失败');
                            $modal.modal('close');
                            //失败
                        }
                    });
                },
                // closeOnConfirm: false,
                onCancel: function () {
                }
            });
        }
        //购物车商品数量增加按钮事件
        $scope.AddBtn = function (index, product) {
            cartProductFactory.setProductQuantity(product, product.number, product.number + 1).then(function (data) {
                if (data.code == 0) {
                    $scope.RunData();//重新加载购物车数据
                } else {
                    $scope.Alertmsg = "商品库存不足，最多只能购买" + product.number + '件';
                    var $modal = angular.element("#my-alert");
                    $modal.modal();
                }
            });

        }
        //购物车商品数量减按钮事件
        $scope.MinusBtn = function (index, product) {
            if (product.number - 1 <= 0) {
                //询问确定不买了吗
                var $modal = angular.element("#my-confirm");
                $modal.modal({
                    relatedTarget: this,
                    onConfirm: function (options) {
                        //确定删除执行
                        cartProductFactory.trashProduct(product).then(function (data) {
                            if (data.code == 0) {
                                //成功
                                $scope.RunData();//重新加载购物车数据
                            } else {
                                $modal.modal('close');
                                //失败
                            }
                        });
                    },
                    // closeOnConfirm: false,
                    onCancel: function () {
                    }
                });

            } else {
                cartProductFactory.setProductQuantity(product, product.number, product.number - 1).then(function (data) {
                    if (data.code == 0) {
                        product.number--;
                        $scope.RunData();//重新加载购物车数据
                    } else {
                        $scope.Alertmsg = "商品库存不足，最多只能购买" + product.number + '件';
                        var $modal = angular.element("#my-alert");
                        $modal.modal();
                    }
                });
            }
        }
        //购物车商品数量直接调整按钮
        $scope.ChangeText = function (product) {
            if (product.inputnumber > 0) {
                cartProductFactory.setProductQuantity(product, product.number, product.inputnumber).then(function (data) {
                    if (data.code == 0) {
                        $scope.RunData();//重新加载购物车数据
                    } else {
                        var sum = parseInt(product.inventory) + parseInt(product.number);
                        $scope.Alertmsg = "商品库存不足，最多只能购买" + sum + '件';
                        var $modal = angular.element("#my-alert");
                        $modal.modal();
                        product.inputnumber = product.number;
                    }
                });
            } else {
                product.inputnumber = product.number;
            }
        }
        //购物车商品选择按钮事件
        $scope.CheckBtn = function (index, product) {
            $scope.checkAllStatus = false;
            cartProductFactory.selectedProduct(product).then(function (data) {
                $scope.RunData();//重新加载购物车数据
                //执行代码
            })
        }
        //购物车商品选择按钮事件
        $scope.CheckAllBtn = function () {
            //执行代码
            /* for (i in  $scope.CartProductArray) {
             if ($scope.CartProductArray[i].mold != 2) {
             $scope.CartProductArray[i].checked = $scope.checkAllStatus;
             }
             }*/
            cartProductFactory.selectedAllProduct($scope.checkAllStatus).then(function (data) {
                if (data.code == 0) {

                    $scope.RunData();//重新加载购物车数据
                }
            })

        }

        //随心配，果汁类商品必须满足数量2份
        $scope.filter=function(){
            var gzcondition={flag:false,sum:0};
            var sxpcondition={flag:false,sum:0};
            var wmcondition={flag:false,sum:0};
            for (var i in   $scope.CartProductArray) {
                /*if(($scope.CartProductArray[i].cid==1) && $scope.CartProductArray[i].checked==true){
                    gzcondition.flag=true;
                    gzcondition.sum=gzcondition.sum+ $scope.CartProductArray[i].number;
                }*/
                if($scope.CartProductArray[i].cid==5 && $scope.CartProductArray[i].checked==true){
                    sxpcondition.flag=true;
                    sxpcondition.sum=sxpcondition.sum+1;//$scope.CartProductArray[i].number;
                }
                if(($scope.CartProductArray[i].cid==23||$scope.CartProductArray[i].cid==18 || $scope.CartProductArray[i].cid==19 || $scope.CartProductArray[i].cid==20) && $scope.CartProductArray[i].checked==true){
                    wmcondition.flag=true;
                    wmcondition.sum=wmcondition.sum + ($scope.CartProductArray[i].price* $scope.CartProductArray[i].number);
                }
            }
            if(gzcondition.flag==true && gzcondition.sum<2){
                alert("果汁商品需要购买2杯起才能派送哦！再去买一杯吧!");
                return false
            }

            if(sxpcondition.flag==true && sxpcondition.sum<2){
                alert("随心配商品需要购买2份起，不一样的才能派送哦！再去买一份吧!");
                return false
            }
            if(wmcondition.flag==true && wmcondition.sum<20){
                alert("外卖商品需满20元才能派送哦！再去买一份吧!");
                return false
            }

            return true;
        }
    }]);

//创建工厂/Service
//获取满减活动数据
grApp.factory('ActivityRuleMJFactory', ['$http', '$q', function ($http, $q) {
    var _code; //返回code状态
    var _discountPrice; //返回优惠金额
    var _ruleArray; //返回规则列表
    var service = {};
    service.getActivityRuleMJ = function (GoodsPrice) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/getActivityRuleMJAjax',
            params: {GoodsPrice: GoodsPrice}
        }).success(function (data, status, headers, config) {
            _code = data.code;
            _discountPrice = data.discountPrice;
            _ruleArray = data.ruleArray;
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.getCode = function () {
        return _code;
    }
    service.getDiscountPrice = function () {
        return _discountPrice;
    }
    service.getRuleArray = function () {
        return _ruleArray;
    }
    return service;
}]);
//获取满送活动数据
grApp.factory('ActivityRuleMSFactory', ['$http', '$q', function ($http, $q) {
    var _ruleArray; //返回规则列表
    var service = {};
    service.getActivityRuleMS = function (GoodsPrice) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/getActivityRuleMSAjax',
            params: {GoodsPrice: GoodsPrice}
        }).success(function (data, status, headers, config) {
            _ruleArray = data.ruleArray;
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.getRuleArray = function () {
        return _ruleArray;
    }
    return service;
}]);
//获取购物车商品数据
grApp.factory('CartProductFactory', ['$http', '$q', function ($http, $q) {
    var _code; //返回code状态
    var _rows; //购物车商品行数
    var _productArray; //购物车数据数组
    var service = {};
    //清理购物车数据
    service.setProductCheck = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/setProductCheckAjax'
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    },
        //获取购物车选择商品金额
        service.getGoodsPrice = function () {
            var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
            $http({
                method: 'GET',
                url: '/cart/getGoodsPriceAjax'
            }).success(function (data, status, headers, config) {
                deferred.resolve(data);
            }).
                error(function (data, status, headers, config) {
                    deferred.reject(data);
                });
            return deferred.promise;
        }
    //获取购物车商品数据
    service.getProductList = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/getProductListAjax'
        }).success(function (data, status, headers, config) {
            _code = data.code;
            _rows = data.rows;
            _productArray = data.ProductArray;
            deferred.resolve(data.rows);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //获取购物车商品行数
    service.getRows = function () {
        return _rows;
    }

    //获取购物车数据数组
    service.getProductArray = function () {
        return _productArray;
    }
    //删除商品
    service.trashProduct = function (Product) {

        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/delCartProductAjax',
            params: {CartProductId: Product.objectId}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    //修改商品数量
    service.setProductQuantity = function (Product, oldNumber, newNumber) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/setProductQuantityAjax',
            params: {CartProductId: Product.objectId, NumberOld: oldNumber, NumberNew: newNumber}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    //选择商品与否
    service.selectedProduct = function (Product) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/setProductCheckedAjax',
            params: {CartProductId: Product.objectId, Checked: Product.checked}
        }).success(function (data, status, headers, config) {
            _code = data.code;
            _rows = data.rows;
            _productArray = data.ProductArray;
            deferred.resolve(data.rows);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;

    };
    //选择全部商品
    service.selectedAllProduct = function (checked) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/cart/setProductCheckedAllAjax',
            params: {Checked: checked}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    return service;
}]);